import urllib, csv, re
from BeautifulSoup import BeautifulSoup

def spot(s):    
    s = s.lower()
    url = 'http://finance.yahoo.com/q?s=' + s
    optionsPage = urllib.urlopen(url)
    #print optionsPage
    soup = BeautifulSoup(optionsPage)
    optionsTable = [[x.text for x in y.parent.contents] for y in soup.findAll('span', attrs={"id" : 'yfs_l84_' + s })]
    #print 'Spot for ' + s + '= ' + str(optionsTable)
    output = str(optionsTable)
    output = output.replace(']]','')
    output = output.replace('[[u','')
    return output

def rev(s):
    try:
        s = s.lower()
        url = 'http://finance.yahoo.com/q?s=' + s
        url = "http://finance.yahoo.com/q/is?s=" + s + "+Income+Statement&annual"
        optionsPage = urllib.urlopen(url)
        soup = BeautifulSoup(optionsPage)
        y = soup.findAll('tr')
        
        for i in y:
            if "Period Ending" in i:
                print i
            elif "Total Revenue" in i:
                print i
        y2 = soup.findAll('th')
        output = []
        to_parse =  soup.findAll('table', attrs={"class" : 'yfnc_tabledata1' })
        to_parse = str(to_parse)
        
        y = to_parse[to_parse.index('Period Ending'):to_parse.index('Total Revenue')]
        y2 = y.split('</th>')
        year = []
        for tmpyear in y2:
            if 'font-weight:bold">' in tmpyear:
                #year = re.sub(r'\s', '', year)
                output.append(tmpyear[tmpyear.index('font-weight:bold">')+len('font-weight:bold">'):])
        
        
        x = to_parse[to_parse.index('Total Revenue'):to_parse.index('Cost of Revenue')]
        y = x.split('&nbsp;&nbsp;')
        for rev in y:
            if "<strong>" in rev:
                rev = re.sub(r'\s', '', rev)
                output.append(rev[rev.index('<strong>')+8:])
         
        toparse2 = re.sub(r'\s', '', to_parse)       
        x = toparse2[toparse2.index('NetIncome<'):toparse2.index('PreferredStockAndOtherAdjustments')]
        y = x.split('&nbsp;&nbsp;')
        for rev in y:
            if '"right"><strong>' in rev:
                rev = re.sub(r'\s', '', rev)
                rev = rev.replace('</strong></td></tr><tr><tdcolspan="2">','')
                output.append(rev[rev.index('<strong>')+8:])
                        
    except:
        pass
    output.append(url)
    return output

def name(s):    
    s = s.lower()
    url = 'http://finance.yahoo.com/q?s=' + s
    optionsPage = urllib.urlopen(url)
    #print optionsPage
    soup = BeautifulSoup(optionsPage)
    optionsTable = [[x.text for x in y.parent.contents] for y in soup.findAll('div', attrs={"class" : 'title'})]
    #print 'Spot for ' + s + '= ' + str(optionsTable)
    output = str(optionsTable)
    output = output.replace(']]','')
    output = output.replace('[[u','')
    return output